<template>
  <div>
 <el-row :gutter="24">
   <el-col :span="18">
     <el-card class="box-card" shadow="always"  style="max-height: 400px;overflow: auto;height: 300px;width: 100%">
       <div slot="header" class="clearfix">
         <span style="font-size: 20px">发送联系人</span>
         <el-button style="padding: 3px 0;float: right" type="text" @click="selectContacts">选择全部</el-button>
         <el-button style="padding: 3px 0;float: right" type="text" @click="clearContacts">清除全部</el-button>

       </div>
       <draggable :list="list2" :options="{group:{name:'article'}, disabled: disabled}"
                  @start="start22"
                  @end="end22"
                  class="dragArea11"
                  style="height: 100px">
         <el-tag
           style="margin-right: 5px"
           :key="index"
           v-for="(tag,index) in list2"
           closable
           :disable-transitions="false"
           @close="handleDel(index, tag.id)">
           {{tag.name}}
         </el-tag>
       </draggable>
     </el-card>
     <el-form  :model="form" label-width="180px" ref="dataForm" :rules="dataRule" style="margin-top: 50px">
       <el-row>
       <el-form-item label="短信模版" prop="template">
         <el-select v-model="form.template" placeholder="请选择短信模版" @change="changeTemplateText">
           <el-option v-for="(item, index) in templates" :key="index" :label="item.name"
                      :value="item.id" :disabled="item.disabled"></el-option>
         </el-select>
       </el-form-item>
         <el-col :span="18">
       <el-form-item :key="index" :label="'替换${'+item+'}内容'" v-for="(item,index) in codeStr" :prop="item">
<!--         <el-input type="text" v-model="param[item]" :placeholder="'请输入替换模版中${'+item+'}的内容'" @input="replace(item)"></el-input>-->
         <el-input type="text" v-model="form[item]" :placeholder="'请输入替换模版中${'+item+'}的内容'" @input="replace(item)"></el-input>
       </el-form-item>
         </el-col>
         <el-col :span="18">
       <el-form-item label="模版显示 :">
         <span>{{templateText1}}</span>
       </el-form-item>
         </el-col>
         <el-col :span="18" v-if="showHint">
           <el-form-item>
             <span style="color: #c6ccd4;font-size: 5px">计费说明：当前内容字数为<span style="color: orange">{{smsgMessageWord}}</span>，按照<span style="color: orange">{{smsgNumber}}</span>条短信发送并计费。</span>
           </el-form-item>
         </el-col>
         <el-col :span="18">
       <el-form-item>

         <el-button type="primary" @click="onSubmit">立即发送</el-button>
         <el-button @click="close" >取消</el-button>

       </el-form-item>
         </el-col>

       </el-row>
     </el-form>
    </el-col>
   <el-col :span="6" >
     <el-card class="box-card" style="max-height: 700px;overflow: auto;height: 800px;width: 100%" >
       <span style="font-size: 30px;align-content: center;text-align: center;margin-bottom: 10px;display: block">联系人</span>
       <el-collapse accordion>
         <draggable :list="list3" :options="{group:{name: falgs,pull:'clone'},filter: '.undraggable', sort: false}"
                    @end="end1"
                    class="dragArea">
           <el-collapse-item :title="list.name" :name="index" v-for="(list,index) in contacts">
             <draggable :list="list.children"
                        :options="{group:{name: falgs,pull:'clone'},filter: '.undraggable', sort: false}"
                        @end="end"
                        class="dragArea">
               <div v-for="(element,index1) in list.children" :key="element.id"
                    :class="{undraggable : element.flag}"
                    class="list-complete-item"
                    :index="index1"
               >
                 <div class="list-complete-item-handle2"> {{element.name}} </div>
               </div>
             </draggable>
           </el-collapse-item>
         </draggable>
       </el-collapse>
     </el-card>
   </el-col>
 </el-row>

  </div>
</template>

<script>
import draggable from "vuedraggable/src/vuedraggable";
export default {
  name: "clone",
  display: "Clone",
  order: 2,
  components: {
    draggable
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'lable',
      },
      falgs: 'article',
      disabled: false,
      list2:[],
      smsgNumber:1,
      smsgMessageWord:50,
      showHint:false,
      selectOrCancel:'选择',
      isSelect:false,
      param: {},
      codeStr:[],
      templateText:"",
      templateText1:"",
      tempKey: -666666, // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
      form: {
        template:'',
        text:'',
        code:''
      },
      sendMessage:{
        smsgMessageTemplate:{},
        contacts:[],
        content:""
      },
      textarea: '',
      templates: [],
      value: '',
      contacts:[],
      activeNames1: ['1'],
      list3:[],
      activeNames: [],
      count: 0,
      dataRule: {
        template: [{ required: true, message: '请选择模版', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getTemplateList();
    this.getgroup();
  },

  methods: {
    log: function (evt) {
      console.log(evt);
      if (evt.added) {
        this.count += 1;
        const item = evt.added.element;
        // 遍历原来的数组删除它
/*        console.log(this.contacts)
        for(var i=0;i<this.contacts.length;i++){
          var contact=this.contacts[i].users;
          for(var j=0;j<contact.length;j++){
            if(item.id==contact[j].id){
              this.contacts[i].users[j]={}
            }
          }
        }*/
        const idx = this.list2.findIndex(e => e.id === item.id);
        let temp = JSON.parse(JSON.stringify(this.list2));
        temp[idx].id = this.count;
        this.list2 = temp;
      }
    },
    select(){
      if(this.isSelect==false){
        this.isSelect=true
        this.selectOrCancel="取消"

      }else {
        this.isSelect=false
        this.selectOrCancel="选择"
        this.$refs.menuListTree.setCheckedKeys([])
        this.list2=[]
      }

    },

    selecedContacts(){
      var ids=[].concat(this.$refs.menuListTree.getCheckedKeys(true,false)); //[].concat(this.$refs.menuListTree.getCheckedKeys(true,false),[this.tempKey])
      this.$http({
        url: this.$http.adornUrl('/smsgcontact/listByIds'),
        method: 'post',
        data: this.$http.adornData(ids,false),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.list2=data.list;
          this.isSelect=false
          this.selectOrCancel="选择"
        } else {
        }
      })

    },

    updateChecked(object,index){
      if(object.isOne){
        // 选中的为组，选中下面的所有组
        for (let i = 0; i < this.contacts[index].children.length; i++) {
          this.contacts[index].children[i].cchecked=!(this.contacts[index].children[i].cchecked)
        }
      }
      console.log(this.contacts)
    },
    //获取组
    getgroup () {
      this.$http({
        url: this.$http.adornUrl('/smsggroup/group'),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.contacts=data.list;
          for (let i = 0; i < this.contacts.length; i++) {
            this.contacts[i].lable=this.contacts[i].name
            for (let j = 0; j <this.contacts[i].children.length; j++) {
              this.contacts[i].children[j].lable=this.contacts[i].children[j].name+" : "+this.contacts[i].children[j].phone
            }
          }
        } else {
        }
        console.log(this.contacts)
      })
    },
    deleteItem: function (index) {
      this.list2.splice(index, 1);
    },
    clearContacts(){
      this.list2=[]
      },
    selectContacts(){
      this.list2=[]
      for(var i=0;i<this.contacts.length;i++){
        var contact=this.contacts[i].children;
        for (let j = 0; j < contact.length; j++) {
          this.list2.push(contact[j])
        }
      }
    },
    close(){
      this.$router.push({ path: '/smsgmessagelog' })
    },
    handleChange(val) {
      console.log(val);
    },
    changeTemplateText(value) {
      this.showHint=true
      this.dataRule={ template: [{ required: true, message: '请选择模版', trigger: 'blur' }]}
      for (var i = 0; i < this.templates.length; i++) {
        var template = this.templates[i];
        if (value === template.id) {
          this.templateText = template.content
          this.sendMessage.smsgMessageTemplate = template
          this.templateText1 = this.templateText
          this.codeStr = []
          this.smsgMessageWord=this.sendMessage.smsgMessageTemplate.content.length
        }
      }

      var content=this.sendMessage.smsgMessageTemplate.content
      var index = content.indexOf("${");
      if(index!=-1){
          this.codeStr=this.getCode(content);
        // 动态添加校验
        for (let i = 0; i < this.codeStr.length; i++) {
          this.dataRule[this.codeStr[i]]=[{ required: true, message: '请输入替换模版中${'+this.codeStr[i]+'}的值', trigger: 'blur' }]
        }
        var template1 = this.form.template;

        this.form={}
        this.form.template=template1
      }
      this.param = {}
/*      var str = this.sendMessage.smsgMessageTemplate.replaceCode
      if (str != "") {
        var strs = new Array();
        strs = str.split(",")
        this.codeStr = strs;
      }*/

    },
    getCode(str){
      var reg = /\$\{(.+?)\}/g
      var list = []
      var result = null
      do {
        result = reg.exec(str)
        result && list.push(result[1])
      } while (result)
      return list
    },
    getTemplateList() {
      this.$http({
        url: this.$http.adornUrl('/smsg/smsgmessagetemplate/getListAll'),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.templates = data.templates;
        }
      })
    },
    replace(value) {
      if (this.templateText != "") {
        //替换模版中的${value}
        var text=this.templateText.format(this.form)
        this.templateText1 = text
        this.smsgMessageWord=this.templateText1.length;
        if(this.templateText1.length>70){
          this.smsgNumber=2
        }else {
          this.smsgNumber=1
        }
      }
    },
    test(value) {
      const item = value;
      console.log(item.id)
      const idx = this.list2.findIndex(
        e => e.id === item.id
      );
      console.log(idx)
      let temp = JSON.parse(JSON.stringify(this.list2));
      temp[idx].id = this.count;
      this.list2 = temp;
    },
    end (ev) {

      /*        if (ev.to.className === 'dragArea11') {
                this.$set(this.testList.users[ev.oldIndex], 'flag', true)
              }*/
      /*    console.log(ev);*/
      /*        var user={"id":"23452","name":"sdfs","phone":"345345"}
              this.list1.push(user)*/


    },
    end1 (ev){
      if (ev.to.className === 'dragArea11') {
        var length = this.list2.length;
        var listElement = this.contacts[ev.oldIndex];
        var users = listElement.children;
        for (var i = 0; i < users.length; i++) {
          this.list2.push(users[i]);
        }
      }
    },
    start22 (event) {
      this.falgs = '222222'
    },
    end22 (ev) {
      this.falgs = 'article'
    },
    handleDel (index, id) {
      this.list2.splice(index, 1)
      let q = this.list2.find((value, index, arr) => {
        return value.id === id
      })
      /* this.$set(q, 'flag', false)*/
    },

    onSubmit() {
      this.sendMessage.contacts = this.list2;
      this.sendMessage.content = this.form.text

      for (let i = 0; i < this.codeStr.length; i++) {
        this.param[this.codeStr[i]]=this.form[this.codeStr[i]]
      }
      if(this.list2.length<=0){
        this.$message({
          message: '请选择联系人',
          type: 'error',
          duration: 1500,
        })
      }else if(this.list2.length>100){
        this.$message({
          message: '联系人不能超过100',
          type: 'error',
          duration: 1500,
        })
      }else {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
        this.$http({
        url: this.$http.adornUrl('/smsg/SendSmsgMessage/sendSmsg'),
        method: 'post',
        data: this.$http.adornData({
          'contacts': this.sendMessage.contacts,
          'smsgMessageTemplate': this.sendMessage.smsgMessageTemplate,
          'param': this.param,
          'content':this.templateText1
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '发送成功',
            type: 'success',
            duration: 1500,
          })
          this.$router.push({ path: '/smsgmessagelog' })
        } else {
          this.$message.error(data.msg)
        }
      })
          }
        })
      }



    }
  }
};
String.prototype.format = function() {
  if(arguments.length == 0) return this;
  var obj = arguments[0];
  var s = this;
  for(var key in obj) {
    s = s.replace(new RegExp("\\${" + key + "\\}", "g"), obj[key]);
  }
  return s;
}


</script>
<style scoped>

.list-group {
  display: flex;
  flex-direction: column;
  padding-left: 0;
  margin-bottom: 0;
  border: 0;
}
.list-group2 {
  display: flex;
  flex-wrap:wrap;
  flex-direction: row;
  padding-left: 0;
  margin-bottom: 0;
  border: 0;
}

.list-group-item:first-child {
  border-top-left-radius: 0.25rem;
  border-top-right-radius: 0.25rem;
}

.list-group-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
}

.list-group-item3 {
  position: relative;
  display: inline-block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
  width: 100px;
  border-radius: 25px;
  background-color: #ece3dc;
}

.el-collapse-item__header {
  border: 0;
}



.list-group-item {
  cursor: move;
}

h3 {
  font-size: 28px;
  margin-bottom: 20px;
}

.el-icon-circle-close {
  color: #c9a2a2;
  font-size: 20px;
  position: absolute;
  right: 30px;
  pointer-events: auto;
  line-height: 50px;

}
.item {
  margin-top: -16px;
  margin-right: -20px;
}

.el-icon-circle-close:hover {
  color: #f40;
}

.el-icon-arrow-right:before{

  dislpay:none !important;
  content: none;
  position:absolute;
  z-index:-999;
}
.el-collapse-item__arrow::before{
  dislpay:none !important;
}

.sortable-chosen{
  dislpay:none !important;
}
.sortable-ghost{
  dislpay:none !important;
}
.el-tree /deep/ .el-tree-node__content{
  position: relative;
  display: block;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
  height: 40px;
  line-height: 40px;
}
.list-complete-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
}

/*.list-complete-item.sortable-chosen {
  background: #4AB7BD;
}

.list-complete-item.sortable-ghost {
  background: #30B08F;

}
.undraggable {
  background-color: red;
}*/

.list-complete-enter,
.list-complete-leave-active {
  opacity: 0;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}


</style>
